#!/bin/bash

# 处理多模态文件并生成对应的消息结构
MULTIMODAL_MESSAGES=""

if [ ${#MULTIMODAL_FILES[@]} -gt 0 ]; then
    for filepath in "${MULTIMODAL_FILES[@]}"; do
        echo "$filepath"
    done
    echo
    read -p "确认上传这些多模态文件(文本/图片/PDF)吗? [Y/n] " confirm_multimodal
    confirm_multimodal=${confirm_multimodal:-Y}
    
    if [[ "$confirm_multimodal" =~ ^[Yy]$ ]]; then
        # 构建多模态消息内容
        CONTENT_ARRAY="[]"
        
        # 添加文本提示（如果有）
        if [ -n "$rfm_AI_MODEL_prompt" ]; then
            CONTENT_ARRAY=$(echo "$CONTENT_ARRAY" | jq --arg text "$rfm_AI_MODEL_prompt" '. += [{"type": "text", "text": $text}]')
        fi
        
        # 添加多模态文件
        for filepath in "${MULTIMODAL_FILES[@]}"; do
            filename=$(basename "$filepath")
            mime_type=$(file -b --mime-type "$filepath")
            
            # 将文件转换为base64
            base64_data=$(base64 -w 0 "$filepath")
            
            if [[ "$mime_type" =~ ^image/ ]]; then
                # 图片文件
                CONTENT_ARRAY=$(echo "$CONTENT_ARRAY" | jq --arg data "$base64_data" --arg type "$mime_type" '. += [{"type": "image_url", "image_url": {"url": "data:\($type);base64,\($data)"}}]')
            elif [[ "$mime_type" == "application/pdf" ]]; then
                # PDF文件 - 需要检查API是否支持
                echo "注意：PDF文件支持可能需要特定模型版本" >&2
                CONTENT_ARRAY=$(echo "$CONTENT_ARRAY" | jq --arg data "$base64_data" --arg filename "$filename" '. += [{"type": "document", "document": {"data": $data, "filename": $filename}}]')
            else
                # 其他文件类型作为文本处理
                file_content=$(cat "$filepath" 2>/dev/null)
                if [ $? -eq 0 ]; then
                    CONTENT_ARRAY=$(echo "$CONTENT_ARRAY" | jq --arg text "$file_content" --arg filename "$filename" '. += [{"type": "text", "text": "=== 文件: \($filename) ===\n\($text)"}]')
                else
                    echo "警告：无法读取文件内容: $filepath" >&2
                fi
            fi
        done
        
        # 创建完整的消息对象
        MULTIMODAL_MESSAGES=$(echo "{}" | jq --argjson content "$CONTENT_ARRAY" '.role = "user" | .content = $content')
    fi
fi
